﻿using DeYi.NuGet.Json;
using DeYi.NuGet.JsonReturn;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace DeYi.NuGet.Other
{
    public class QiniuHelper
    {
        /// <summary>
        /// 获得七牛Token
        /// </summary>
        /// <param name="AccessKey"></param>
        /// <param name="SecretKey"></param>
        /// <param name="Scope">空间bucket名</param>
        /// <param name="PersistentOps">持久化策略</param>
        /// <returns></returns>
        public static string GetQiniuToken(string AccessKey, string SecretKey, string Scope, string PersistentOps = "")
        {
            Mac mac = new Mac(AccessKey, SecretKey);
            PutPolicy putPolicy = new PutPolicy();
            putPolicy.Scope = Scope;
            putPolicy.SetExpires(7200);
            //图片加水印API地址：https://developer.qiniu.com/dora/1316/image-watermarking-processing-watermark#7
            if (!string.IsNullOrEmpty(PersistentOps))
            {
                putPolicy.SetExpires(3600);
                putPolicy.PersistentOps = PersistentOps;//"watermark/2/text/5LiD54mb5LqR5a2Y5YKo/fontsize/400";
            }
            return Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
        }

        /// <summary>
        /// 七牛云转存文件：加不了水印
        /// </summary>
        /// <param name="sourcePicUrl">钉钉http地址</param>
        /// <param name="desFileName"></param>
        /// <param name="AccessKey"></param>
        /// <param name="SecretKey"></param>
        /// <param name="QiniuScope"></param>
        /// <returns></returns>
        public static async Task<bool> QiniuFetchFile(string sourcePicUrl, string desFileName, string AccessKey, string SecretKey, string QiniuScope)
        {
            // 设置存储区域
            Config config = new Config();
            config.Zone = Zone.ZONE_CN_South;//文件默认存放华南区域
            Mac mac = new Mac(AccessKey, SecretKey);
            BucketManager bucketManager = new BucketManager(mac, config);

            // 公网可访问的文件链接
            string resUrl = sourcePicUrl;
            // 存储空间名
            string Bucket = QiniuScope;
            // 文件名
            string Key = desFileName;// Path.GetFileName(dingPicUrl);
            FetchResult ret = bucketManager.Fetch(resUrl, Bucket, Key);

            if (ret.Code != (int)HttpCode.OK)
            {
                LogHelper.RunLog(ret.Text, "QiniuFetchFile报错");
                LogHelper.RunLog(JsonHelper.Serialize(ret), "QiniuFetchFile结果");
            }
            return ret.Code == (int)HttpCode.OK;
        }


        /// <summary>
        /// 七牛云上传文件：可加水印
        /// </summary>
        /// <param name="sourceFilePath">前端base64存本地后的路径</param>
        /// <param name="desFileName"></param>
        /// <param name="AccessKey"></param>
        /// <param name="SecretKey"></param>
        /// <param name="QiniuScope"></param>
        /// <param name="waterMarkText"></param>
        public static JsonReturn<bool> QiniuUploadFile(string sourceFilePath, string desFileName, string AccessKey, string SecretKey, string QiniuScope, string waterMarkText = "")
        {
            Mac mac = new Mac(AccessKey, SecretKey);
            // 上传文件名
            string key = desFileName;
            // 本地文件路径
            string filePath = sourceFilePath;
            // 存储空间名
            string Bucket = QiniuScope;

            //文字水印持久化策略
            var PersistentOps = "";
            if (!string.IsNullOrEmpty(waterMarkText))
            {
                //文字铺排水印示例：watermark/4/text/5LiD54mb5LqR5a2Y5YKo/fontsize/400/fill/Z3JheQ==/dissolve/50/rotate/30/uw/180/uh/180/resize/1
                //注意使用安全的base64编码：base64text.Replace("+","-").Replace("/", "_")
                PersistentOps = "watermark/4/text/" +
                Convert.ToBase64String(Encoding.Default.GetBytes(waterMarkText)).Replace("+", "-").Replace("/", "_") + "/fontsize/400/fill/Z3JheQ==/dissolve/50/rotate/30/uw/180/uh/180/resize/1|saveas/" + Convert.ToBase64String(Encoding.Default.GetBytes(Bucket + ":" + desFileName)).Replace("+", "-").Replace("/", "_");

                //如果上面没有使用saveas参数：那么只能通过http://api.qiniu.com/status/get/prefop?id=<persistentId>获取带水印的图片
                //上传完会返回给你persistentId结果值
            }
            // 生成上传token
            string token = GetQiniuToken(AccessKey, SecretKey, Bucket, PersistentOps);

            Config config = new Config();
            // 设置上传区域
            config.Zone = Zone.ZONE_CN_South;//文件默认存放华南区域
            // 设置 http 或者 https 上传
            config.UseHttps = true;
            config.UseCdnDomains = true;
            config.ChunkSize = ChunkUnit.U512K;

            //string tempPath = System.IO.Path.GetTempPath();//做法比较坑，先上传临时目录，然后传七牛云
            //int rnd = new Random().Next(1, 100000);
            //string filePath = tempPath + "resumeFile" + rnd.ToString();
            //char[] testBody = new char[4 * 1024 * 1024];
            //System.IO.FileStream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create);
            //System.IO.StreamWriter sw = new System.IO.StreamWriter(stream, System.Text.Encoding.Default);
            //sw.Write(testBody);
            //sw.Close();
            //stream.Close();


            // 表单上传
            FormUploader target = new FormUploader(config);
            HttpResult result = target.UploadFile(filePath, key, token, null);
            //Console.WriteLine("form upload result: " + result.ToString());
            if (result.Code != (int)HttpCode.OK)
            {
                LogHelper.RunLog(result.Text, "QiniuUploadFile报错");
                LogHelper.RunLog(JsonHelper.Serialize(result), "QiniuUploadFile结果");
                return new JsonReturn<bool>() { Data = false, Msg = JsonHelper.Serialize(result) };
            }

            return new JsonReturn<bool>() { Data = true, Msg = JsonHelper.Serialize(result) };
        }
    }
}
